//
//  PwdForgetViewController.m
//  baiduhealth
//
//  Created by longcheng on 14-7-11.
//  Copyright (c) 2014年 Baidu. All rights reserved.
//

#import "PwdForgetViewController.h"
//#import "RegViewController.h"
//#import "HTTPFacade.h"
//#import "BHError.h"
//#import "ImageDefine.h"
//#import "BDImage.h"
//#import "BaseRequestModel.h"
//#import "UserRequestModel.h"
//#import "UINavigationItem+CustomTitleLabel.h"
//#import "UserManage.h"
#import "PwdResetViewController.h"
#import "CKHttpCommunicate.h"
//#import "LoginDefine.h"
//#import "ErrorCodeManager.h"
#import "JrdDatamanager.h"
#import "UIColor+JRDNote.h"
#import "UIColor-Adaptive.h"
#import "StringHelper.h"

//#import "ASIReachability.h"

#define PHONE_MAXLENGTH 11
#define PASSWORD_MAXLENGTH 14
#define PASSWORD_MINLENGTH 6
#define TAG_CAPTCHA 2

@implementation PwdForgetViewController {
    NSInteger loginType;
    NSInteger _verifyCount;

    // NSString *_phonenum;
    NSString *_password;

    CGRect scroBounds;
}

@synthesize scroView = _scroView;
@synthesize txtEmail = _txtEmail;
@synthesize txtCaptcha = _txtCaptcha;
//@synthesize txtPassword = _txtPassword;
@synthesize vCodeStr = _vCodeStr;
@synthesize nextBtn = _nextBtn;
@synthesize captchaActivity = _captchaActivity;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _headText.text = NSLocalizedString(@"login_login_forgotpassword", nil);
    _txtEmail.delegate = self;
    _txtCaptcha.delegate = self;
    _txtCaptcha.tag = TAG_CAPTCHA;
    [self iniView];
    [self initGesture];
    [self configureViews];


}

- (void)configureViews{
    
    self.closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.closeButton setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    [self.closeButton setTintColor:[UIColor whiteColor]];
    self.closeButton.alpha = 0.5;
    [self.view addSubview:self.closeButton];
    @weakify(self);
    [self.closeButton bk_addEventHandler:^(id sender) {
        @strongify(self);
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
}
- (void)viewWillLayoutSubviews {
    self.closeButton.frame = (CGRect){10, 20, 25, 25};
}


- (void)doneBack:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)iniView {

    [self doneChangeCode:nil];
    [self.navigationController setNavigationBarHidden:false];
    [self.navigationItem setTitle:NSLocalizedString(@"login_reset_password", nil)];
    
    //[self.navigationItem setCustomeTitle:JrdLocalizedString(@"S:SmartBand2:login_reset_password", nil)];
    //
    //    self.navigationController.navigationBar.barTintColor = [UIColor JRDColorNavGrayBg];
    //    [self setLeftItemImage:[UIImage imageNamed:@"ic_arrow_left"]
    //             selectedImage:[UIImage imageNamed:@"ic_arrow_left"]
    //                    target:self
    //                    action:@selector(back)];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *leftButtonImage = [UIImage imageNamed:@"ic_arrow_left"];
    button.frame = CGRectMake(0, 0, leftButtonImage.size.width, leftButtonImage.size.height);
    [button setImage:leftButtonImage forState:UIControlStateNormal];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.navigationController.navigationBar.barTintColor = [UIColor JRDColorNavGrayBg];

    [self.view setBackgroundColor:[UIColor whiteColor]];
    loginType = 0;
    [_scroView setBackgroundColor:[UIColor whiteColor]];
    scroBounds = _scroView.frame;
    CGRect bounds = [[UIScreen mainScreen] applicationFrame];
    _scroView = [[UIScrollView alloc] initWithFrame:bounds];

    _scroView.delegate = self;

    [self setTextField:_txtEmail backImage:nil
             placeHoler:NSLocalizedString(@"login_input_email_hint", nil)//JrdLocalizedString(@"S:SmartBand2:login_input_email_hint", nil)
        clearButtonMode:UITextFieldViewModeWhileEditing
           keyboardType:UIKeyboardTypeEmailAddress
          returnKeyType:UIReturnKeyNext];

    [self setTextField:_txtCaptcha backImage:nil placeHoler:NSLocalizedString(@"login_input_captcha_set_hint", nil)//JrdLocalizedString(@"S:SmartBand2:login_input_captcha_set_hint", nil)
        clearButtonMode:UITextFieldViewModeWhileEditing
           keyboardType:UIKeyboardTypeNumberPad
          returnKeyType:UIReturnKeyDone];

    [self setbtnView:_nextBtn
        backgroundImg:nil
            btnTitle:NSLocalizedString(@"login_submit_next", nil)];//JrdLocalizedString(@"S:SmartBand2:login_submit_next", nil)];

    _captchaActivity.hidden = YES;
    _txtCaptcha.hidden= YES;
    _txtEmail.y += 100;
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initImageCode {
    _imageCode.layer.cornerRadius = 23.f;
    //    _imageCode.layer.borderWidth = 1.0f;

    _imageCode.backgroundColor = [UIColor whiteColor];

    UITapGestureRecognizer *imageRefresh = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(getCaptchaImg)];
    imageRefresh.delegate = self;
    imageRefresh.numberOfTapsRequired = 1;
    imageRefresh.numberOfTouchesRequired = 1;
    imageRefresh.cancelsTouchesInView = NO;
    [_imageCode addGestureRecognizer:imageRefresh];
}

- (void)setTextField:(UITextField *)textField
           backImage:(NSString *)bgImage
          placeHoler:(NSString *)placeHolder
     clearButtonMode:(UITextFieldViewMode)clearButtonMode
        keyboardType:(UIKeyboardType)keyboardType
       returnKeyType:(UIReturnKeyType)returnKeyType {

    textField.layer.cornerRadius = 25.0f;
    textField.borderStyle = UITextBorderStyleNone;
    textField.layer.backgroundColor = [UIColor JRDColorLoginTextGray].CGColor;

    textField.textAlignment = NSTextAlignmentCenter;
    textField.placeholder = placeHolder;
    textField.clearButtonMode = clearButtonMode;
    textField.returnKeyType = returnKeyType;
    textField.keyboardType = keyboardType;
}

- (void)setbtnView:(UIButton *)button backgroundImg:(NSString *)bgImgName btnTitle:(NSString *)btnTitle {

    [button setBackgroundColor:[UIColor JRDColorStandardBlue]];
    button.layer.cornerRadius = 25.0f;
    //    button.layer.borderWidth = 1.0f;

    button.titleLabel.textAlignment = NSTextAlignmentCenter;
    [button setTitle:btnTitle forState:UIControlStateNormal];
}

#pragma scroView
#pragma mark KeyBoradNotification
- (void)keyboardShow:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];

    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.
    CGRect keyboardRect = [aValue CGRectValue];

    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];

    CGRect bounds = CGRectMake(0, 0, self.scroView.frame.size.width, keyboardRect.origin.y);

    [self.scroView setFrame:bounds];
}

- (void)keyboardHide:(NSNotification *)notification {
    [_scroView setFrame:scroBounds];

    //_isInput = NO;
}

#pragma mark textField
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [_txtEmail resignFirstResponder];
    [_txtCaptcha resignFirstResponder];

    if (textField.tag == TAG_CAPTCHA) {
        [self nextAction:nil];
    }
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//    [self.nextBtn setAlpha:_txtCaptcha.text.length > 0 ? 1.0f : 0.5f];
    if ([string isEqualToString:@""]) {
        return YES;
    }

    if (textField == _txtCaptcha && textField.text.length >= 4) {
        return NO;
    }
    return YES;
}

#pragma mark CaptchaImg

- (IBAction)doneChangeCode:(id)sender {
    [self getCaptchaImg];
}

- (void)getCaptchaImg {

    /*[self setcaptchaActivityWithStatus:CAPTCHA_START];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //[self imageCode].image = nil;
        HttpCallBack *callback = [[HttpCallBack alloc] init];
        callback.doneBlock = ^(id result, NSUInteger tag) {
            if ([result isKindOfClass:[UserRequestModel class]]) {
                UserRequestModel *model = (UserRequestModel *)result;
                if ([model errorCode] != 0) {
                    
                    [self makeErrCode:model.errorMsg];
                    [self setcaptchaActivityWithStatus:CAPTCHA_END];
                    
                } else {
                    self.vCodeStr = model.vcodeStr;
                    [self getCapthaImageWithUrl:model.vcodeURL];
                }
            } else if ([result isKindOfClass:[BaseRequestModel class]]) {
                NSString *errorStr = JrdLocalizedString(@"S:SmartBand2:getcapthafailed", nil);
                [self makeErrCode:errorStr];
                [self setcaptchaActivityWithStatus:CAPTCHA_END];
            }
        };
        
        [[UserManage sharedUserManage] getCaptchaWithCallback:callback];
    });*/
}

- (void)getCapthaImageWithUrl:(NSString *)url {

    /*[BDImage getImageWithNSUrl:url completion:^(UIImage *image) {
        [self setcaptchaActivityWithStatus:CAPTCHA_END];
        
        UIImage *cImage = image;
        [self imageCode].image = cImage;
        CGRect codeRect = [self imageCode].frame;
        [[self imageCode] setFrame:codeRect];
    }];*/
}

- (void)setcaptchaActivityWithStatus:(NSInteger)captchaStatus {
    /*if (CAPTCHA_START == captchaStatus) {
        _captchaActivity.hidden = NO;
        [_captchaActivity startAnimating];
    } else {
        _captchaActivity.hidden = YES;
        [_captchaActivity stopAnimating];
    }*/
}

- (void)makeErrCode:(NSString *)errcode {
    if ([errcode length] > 0) {
       // [SVProgressHUD showErrorInView:self.view WithStatus:errcode duration:1.5];
    }
}

#pragma mark “Next”按钮 相关

- (BOOL)userInputConform {

    NSString *userName = _txtEmail.text;
    NSString *userCaptha = _txtCaptcha.text;

    if ([userName length] == 0) {
        [self makeErrCode:NSLocalizedString(@"pleaseiyeop", nil)];
        return NO;
    }

    if ([userCaptha length] == 0) {
        [self makeErrCode:NSLocalizedString(@"pleaseicaptha", nil)];
        return NO;
    }

    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (0 != _txtEmail.text.length && 0 != _txtCaptcha.text.length) {
    }
}

- (void)checkEmailFromSever{
    /*NSDictionary *parameter_ = @{
                                 @"userid":[JrdDatamanager manager].user.userId,
                                 @"email":self.txtEmail.text
                                 };
    [CKHttpCommunicate createRequest:HTTP_CHECK_EMAIL WithParam:parameter_ withMethod:GET success:^(id result) {
        if(result){
        }
    }failure:^(NSError *erro) {
        
    } showHUD:self.view];*/
    PwdResetViewController* viewController = [[PwdResetViewController alloc] init];
    
    
    [self presentViewController:viewController animated:YES completion:^{
        
    }];


}

//user click Next button
- (IBAction)nextAction:(id)sender {

    /*if (![self userInputConform]) {
        return;
    }*/
    BOOL isValid = [self isInputAccountValid];
    if (!isValid) {
        //return;
    }
    
    [self checkEmailFromSever];
    
}

- (BOOL)isInputAccountValid {
    BOOL isEmail = [StringHelper isValidateEmail:_txtEmail.text];
    BOOL isPhone = [StringHelper isValidChinesePhone:_txtEmail.text];
    if (isEmail || isPhone) {
        return YES;
    } else {
        [self makeErrCode:NSLocalizedString(@"pleaseiref", nil)];
        return NO;
    }
}

//first check user input email/userName/number is valid
/*- (void)checkUserAccountIsInvalid {
    NSString *email = _txtEmail.text;

    HttpCallBack *callback = [[HttpCallBack alloc] init];
    callback.doneBlock = ^(id result, NSUInteger tag) {
        if ([result isKindOfClass:[UserRequestModel class]]) {
            UserRequestModel *model = (UserRequestModel *)result;
            if ( 1 != model.status ) {
                [SVProgressHUD dismiss];
                [self makeErrCode:JrdLocalizedString(@"S:SmartBand2:str_user_not_exist_error", nil)];
            }else{
                [self startPasswordFindBack];
            }
        }
    };
    [[UserManage sharedUserManage] authAccountWithUserName:email callback:callback];
}*/

//then find password back from web
- (void)startPasswordFindBack {
    [self pwdFindBackFromWebWithBlock:^(BOOL isSuccess, NSString *error) {
        if (isSuccess) {
            [self turnToPwdResetViewController];
        } else {
            [self makeErrCode:error];
        }
    }];
}

- (void)pwdFindBackFromWebWithBlock:(void (^)(BOOL isSuccess, NSString *error))resuleBlock {
    NSString *email = _txtEmail.text;
    NSString *captcha = _txtCaptcha.text;

    /*HttpCallBack *callback = [[HttpCallBack alloc] init];
    callback.doneBlock = ^(id result, NSUInteger tag) {
        if ([result isKindOfClass:[UserRequestModel class]]) {
            [SVProgressHUD dismiss];
            UserRequestModel *model = (UserRequestModel *)result;
            if (1 != model.status ) {
                NSString *errorStr;
                NSString *status = [NSString stringWithFormat:@"%@", [model attributeForKey:@"status"]];
                if ([status isEqualToString:@"-5"]) {
                    errorStr = JrdLocalizedString(@"S:SmartBand2:str_login_verification_error", nil);
                    [self txtCaptcha].text = nil;
                    [self getCaptchaImg];
                }else{
                    errorStr = JrdLocalizedString(@"S:SmartBand2:str_user_not_exist_error", nil);
                }
                resuleBlock(NO, errorStr);
            } else {
                resuleBlock(YES, nil);
            }
        }
    };
    [[UserManage sharedUserManage] loginForgetPassword:email imageID:_vCodeStr imageCode:captcha callback:callback];*/
}

- (void)turnToPwdResetViewController {
    /*PwdResetViewController *pwdResetViewController = [[PwdResetViewController alloc] init];
    pwdResetViewController.pwdForgetVC = self;
    pwdResetViewController.emailFromFgtPwd = _txtEmail.text;*/

   // [self.navigationController pushViewController:pwdResetViewController animated:YES];
}

- (void)initGesture {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:tap];
}

- (void)dismissKeyboard {
    [self.view endEditing:YES];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[UITextField class]]) {
        return NO;
    }

    return YES;
}

- (void)returnToLastView {
    if (self.lastView) {
        [self.navigationController popToViewController:self.lastView animated:YES];
    } else {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
@end
